package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.PermissionDao;
import com.atguigu.dao.RolePermissionDao;
import com.atguigu.entity.Permission;
import com.atguigu.entity.RolePermission;
import com.atguigu.helper.PermissionHelper;
import com.atguigu.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl extends BaseServiceImpl<Permission> implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Override
    protected BaseDao<Permission> getEntityDao() {
        return permissionDao;
    }

    @Override
    public List<Map<String, Object>> findPermissionsByRoleId(Long roleId) {
        List<Permission> permissionList = this.permissionDao.findAll();
        //获取当前用户所拥有的权限id
        List<Long> myPermissionIdList = this.rolePermissionDao.findPermissionIdsByRoleId(roleId);
        List zNodes = new ArrayList();
        for(Permission permission:permissionList){
            Map<String ,Object> map = new HashMap();
            map.put("id",permission.getId());
            map.put("pId",permission.getParentId());
            map.put("name",permission.getName());
            map.put("checked",myPermissionIdList.contains(permission.getId()));
            //map.put("open",true);

            zNodes.add(map);
        }
        //返回数据
        return zNodes;
    }

    /**
     * 保存角色权限
     */
    @Override
    public void saveRolePermissionRealtionShip(Long roleId, Long[] permissionIds) {
        rolePermissionDao.deleteByRoleId(roleId);

        for(Long permissionId : permissionIds) {
            if(StringUtils.isEmpty(permissionId)) continue;
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionDao.insert(rolePermission);
        }
    }

    @Override
    public List<Permission> findMenuPermissionByAdminId(Long adminId) {
        List<Permission> permissionList = null;
        if(adminId==1){ //超级管理员 查询所有的权限
            //permissionList = this.permissionDao.findAll();
            permissionList = this.permissionDao.findAllMenu();
        }else{ //到数据库表中查询该用户拥有的权限
            permissionList = permissionDao.findListByAdminId(adminId);
        }
        //2.将列表结构（List）转换为菜单结构（Tree）
        List<Permission> result = PermissionHelper.bulid(permissionList);
        //3.返回菜单结构
        return result;
    }

}
